﻿using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using WeatherHistory.Api.CommandsQueries.Commands.Accounts.Registration;
using WeatherHistory.Shared.Constants;
using WeatherHistory.Shared.Exceptions;
using WeatherHistory.Shared.Helpers;

namespace WeatherHistory.Api.Controllers;

/// <summary>
///     Контроллер для регистрации аккаунта
/// </summary>
[AllowAnonymous]
[Route("registration")]
public class RegistrationController : ApiControllerBase
{
    /// <summary>Регистрация аккаунта</summary>
    [HttpPost]
    [ProducesResponseType(StatusCodes.Status409Conflict)]
    [ProducesResponseType(StatusCodes.Status403Forbidden)]
    [ProducesResponseType(typeof(RegistrationAccountsCommandResponse), StatusCodes.Status201Created)]
    public async Task<ActionResult<RegistrationAccountsCommandResponse>> Post([FromBody] RegistrationAccountsCommandRequest query)
    {
        if (HttpContext.Request.Cookies.ContainsKey("id") ) throw new ForbiddenException("Аккаунт уже авторизован");

        var result = await Mediator.Send(query);
        SecurityHelper.AuthenticateWithCookie(HttpContext, result.Id);
        return Created($"/accounts/{result.Id}", result);
    }
}